package com.wgz.medicalmanagement.infrastructure.security;

import com.wgz.medicalmanagement.domain.entity.User;
import com.wgz.medicalmanagement.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Optional;

/**
 * JWT用户详情服务
 *
 * @author medical
 * @since 2023-05-29
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class JwtUserDetailsService implements UserDetailsService {

    private final UserRepository userRepository;

    /**
     * 根据用户名加载用户详情
     *
     * @param username 用户名
     * @return 用户详情
     * @throws UsernameNotFoundException 如果用户未找到
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(username);
        if (user == null) {
            log.warn("未找到用户: {}", username);
            throw new UsernameNotFoundException("用户名或密码不正确");
        }
        return createUserDetails(user);
    }
    
    /**
     * 从用户实体创建UserDetails对象
     */
    private UserDetails createUserDetails(User user) {
        if (!user.getEnabled()) {
            log.warn("用户 [{}] 已被禁用", user.getUsername());
            throw new UsernameNotFoundException("用户已被禁用");
        }
        
        return new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                user.getPassword(),
                user.getEnabled(),
                user.getAccountNonExpired(),
                user.getCredentialsNonExpired(),
                user.getAccountNonLocked(),
                Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"))
        );
    }
} 